package br.com.documentos.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import br.com.documentos.model.entity.Usuario;
import br.com.documentos.model.service.AtivadorConta;
import br.com.documentos.model.util.StringUtil;

public class AtivacaoServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public static final String EMAIL_PARAM = "id";
	public static final String SENHA_PARAM = "value";
	
	public static final String ENDERECO_ATIVACAO = "/ativacao";
	
	private ApplicationContext applicationContext = null;
       
    public AtivacaoServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String emailCriptografado = request.getParameter(EMAIL_PARAM);
		String senhaCriptografada = request.getParameter(SENHA_PARAM);
		
		if( StringUtil.isNotEmpty(emailCriptografado) && StringUtil.isNotEmpty(senhaCriptografada) ){
			
			if (applicationContext == null){
	            applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
	        }
			
			if( applicationContext != null && applicationContext.containsBean("ativador") ){
				AtivadorConta ativador = (AtivadorConta) applicationContext.getBean("ativador");
				Usuario usuario = ativador.ativarConta(emailCriptografado, senhaCriptografada);
				
				if( usuario != null && usuario.isAtivo() ){
					response.sendRedirect(response.encodeRedirectURL("login.xhtml?id=ativo"));
					return;
				}
			}
		}
		
		response.sendRedirect(response.encodeRedirectURL("login.xhtml?id=ativacaoInvalida"));
	}

}
